﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using NTQOnlineExam.Services.Infrastructure;
using NTQOnlineExam.Services.Models;

namespace NTQOnlineExam.Services.ReportService.Term
{
    public class GetTermDTOsDbCommand : ICommand<SearchResult<TermDTO>>
    {
        private readonly int _pageSize;
        private readonly int _startIndex;
        private readonly string _sorting;

        public GetTermDTOsDbCommand(int startIndex, int pageSize, string sorting)
        {
            _startIndex = startIndex;
            _pageSize = pageSize;
            _sorting = sorting;
        }

        private const string SQL = @"
          WITH PAGING AS (
            SELECT t.TermId, t.TermName, t.Description, t.Price, t.IsPublished, t.YearId, row_number() over (order by {0}) as rownumber
            FROM dbo.Term t)
    ";


        public SearchResult<TermDTO> Execute()
        {
            var connectionString = ConfigurationManager.AppSettings["ConnectionString"];

            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                IList<TermDTO> items = new List<TermDTO>();
                int totalCount = 0;
                SqlCommand cmd = new SqlCommand(BuildQuery(), connection);
                cmd.Parameters.Add("@StartIndex", SqlDbType.Int).Value = _startIndex;
                cmd.Parameters.Add("@PageSize", SqlDbType.Int).Value = _pageSize;
                connection.Open();
                SqlDataReader reader = cmd.ExecuteReader();
                try
                {
                    if (!reader.Read()) return null;
                    totalCount = reader.GetInt32(0);
                    reader.NextResult();

                    while (reader.Read())
                    {
                        items.Add(GetDto(reader));
                    }
                }
                finally
                {
                    reader.Close();
                }
                return new SearchResult<TermDTO>(items, totalCount);
            }
        }

        private TermDTO GetDto(SqlDataReader reader)
        {
            return new TermDTO
            {
                TermId = (int)reader["TermId"],
                TermName = reader["TermName"].ToString(),
                Description = reader["Description"] != DBNull.Value ? reader["Description"].ToString() : string.Empty,
                Price = reader["Price"] != DBNull.Value ? (decimal.Parse(reader["Price"].ToString())) : (decimal?)null,
                IsPublished = (bool)reader["IsPublished"],
                YearId = reader["YearId"] != DBNull.Value ? (int)reader["YearId"] : 0
            };
        }

        private string BuildQuery()
        {
            var query = new StringBuilder();
            var sqlQuery = string.Format(SQL, !string.IsNullOrEmpty(_sorting) ? _sorting : "t.TermId");

            query.AppendFormat("{0} {1};{0} {2}", sqlQuery, @"SELECT COUNT(1) FROM paging", @" SELECT * FROM paging WHERE (@PageSize=0 or rownumber between (@StartIndex+1) and (@PageSize+@StartINdex)) ORDER BY rownumber");
            return query.ToString();
        }
    }
}
